import React, { useState } from "react";
import useSWR from "swr";
import { fetcher } from "../utils";
import { useNavigate } from "react-router-dom";
import "./GradeEdit.css";

function GradeEdit() {
    const navigate = useNavigate();
    const [selectedStudent, setSelectedStudent] = useState("");
    const [selectedCourse, setSelectedCourse] = useState("");
    const [grade, setGrade] = useState("");
    const [isBusy, setBusy] = useState(false);
    const [actionError, setActionError] = useState(null);
    const [semester, setSemester] = useState("");
    // 学期选项，可根据实际需要扩展
    const semesterOptions = [
        "2023秋季", "2023春季", "2022秋季", "2022春季"
    ];

    // 拉取学生和课程数据
    const { data: studentList } = useSWR("/api/student/list", fetcher);
    const { data: courseList } = useSWR("/api/course/list", fetcher);

    // 拉取已有成绩（如已选学生和课程）
    const { data: gradeInfo } = useSWR(
        selectedStudent && selectedCourse ? `/api/grade/one?stu_sn=${selectedStudent}&cou_sn=${selectedCourse}` : null,
        fetcher
    );

    React.useEffect(() => {
        if (gradeInfo && gradeInfo.grade !== undefined) {
            setGrade(gradeInfo.grade);
        } else {
            setGrade("");
        }
    }, [gradeInfo]);

    const handleSave = async () => {
        if (!selectedStudent || !selectedCourse) {
            setActionError("请选择学生和课程");
            return;
        }
        if (!semester) {
            setActionError("请选择学期");
            return;
        }
        setBusy(true);
        setActionError(null);
        try {
            let response = await fetch("/api/grade/one", {
                method: "POST",
                headers: { "Content-Type": "application/json;charset=utf-8" },
                body: JSON.stringify({ stu_sn: parseInt(selectedStudent), cou_sn: parseInt(selectedCourse), grade, semester }),
            });
            if (!response.ok) {
                let errorText = await response.text();
                setActionError(errorText);
                return;
            }
            navigate("/grade/list");
        } finally {
            setBusy(false);
        }
    };

    return (
        <div className="paper">
            <div className="paper-head">
                <h3>录入/修改成绩</h3>
            </div>
            <div className="paper-body">
                <div className="field">
                    <label htmlFor="student">学生：</label>
                    <select 
                        id="student"
                        value={selectedStudent} 
                        onChange={e => setSelectedStudent(e.target.value)}
                    >
                        <option value="">请选择学生</option>
                        {studentList && studentList.map(stu => (
                            <option key={stu.stu_sn} value={stu.stu_sn}>{stu.stu_name}（{stu.stu_no}）</option>
                        ))}
                    </select>
                </div>
                <div className="field">
                    <label htmlFor="course">课程：</label>
                    <select 
                        id="course"
                        value={selectedCourse} 
                        onChange={e => setSelectedCourse(e.target.value)}
                    >
                        <option value="">请选择课程</option>
                        {courseList && courseList.map(cou => (
                            <option key={cou.cou_sn} value={cou.cou_sn}>{cou.cou_name}</option>
                        ))}
                    </select>
                </div>
                <div className="field">
                    <label htmlFor="grade">成绩：</label>
                    <input
                        id="grade"
                        type="number"
                        value={grade}
                        onChange={e => setGrade(e.target.value)}
                        min="0"
                        max="100"
                        placeholder="请输入0-100之间的分数"
                    />
                </div>
                <div className="field">
                    <label htmlFor="semester">学期：</label>
                    <select 
                        id="semester"
                        value={semester} 
                        onChange={e => setSemester(e.target.value)}
                    >
                        <option value="">请选择学期</option>
                        {semesterOptions.map(opt => (
                            <option key={opt} value={opt}>{opt}</option>
                        ))}
                    </select>
                </div>
                {actionError && <div className="error">{actionError}</div>}
            </div>
            <div className="paper-footer">
                <button 
                    className="btn" 
                    onClick={handleSave} 
                    disabled={isBusy}
                >
                    {isBusy ? '保存中...' : '保存'}
                </button>
                <button 
                    className="btn" 
                    onClick={() => navigate("/grade/list")}
                >
                    返回
                </button>
            </div>
        </div>
    );
}

export default GradeEdit; 